package com.stud.framework.aspectj;

import jakarta.servlet.http.HttpServletRequest;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * @author sdx
 * @title
 * @desription 记录方法运行时间切面类
 * @data 2023-03-01 9:24
 */
@Aspect
@Component
@Order(Integer.MIN_VALUE)
public class RecordTimeAspect {
    public static final Logger log = LoggerFactory.getLogger(RecordTimeAspect.class);

    @Around("execution(* com.stud..*Controller.*(..))")
    public Object recordTimeLog(ProceedingJoinPoint joinPoint) throws Throwable {
        // 记录开始时间
        long begin = System.currentTimeMillis();
        // 获得request对象
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes sra = (ServletRequestAttributes) requestAttributes;
        HttpServletRequest req = sra.getRequest();
        Object result = joinPoint.proceed();
        // 记录结束时间
        long end = System.currentTimeMillis();
        long time = end - begin;
        String methodName = joinPoint.getSignature().getName();
        if (!methodName.contains("export") && methodName.contains("Export") && time < 2000) {
            return result;
        }
        if (time >= 2000) {
            log.warn("方法执行时长超过2秒的方法信息:");
            log.warn("类信息:{}", joinPoint.getTarget().getClass());
            log.warn("方法名:{}", joinPoint.getSignature().getName());
            log.warn("请求地址:{}", req.getRequestURI());
            log.warn("{}执行时间为===>{} 秒", methodName, time / 1000.0);
            log.warn("---------------------------------------------------------------------");
        }
        return result;
    }


}
